package com.sam4cloud.oauth2.project.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sam4cloud.oauth2.project.model.entity.OauthUser;
import com.sam4cloud.oauth2.project.service.IOauthUserService;
import com.sam4cloud.common.core.cons.HttpCode;
import com.sam4cloud.common.core.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * @Author: Sam
 * @Date: 2022-11-11 17:39
 * @Description: 用户认证
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IOauthUserService oauthUserService;

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        OauthUser oauthUser = oauthUserService.getOne(Wrappers.<OauthUser>lambdaQuery()
                .eq(OauthUser::getLoginName, loginName), false);
        AssertUtil.isNull(oauthUser, HttpCode.SC_FORBIDDEN, "用户名或密码错误");
        User user = new User(loginName, oauthUser.getPassword(), Arrays.asList(new SimpleGrantedAuthority("admin")));
        return user;
    }
}
